// 广告奖励相关
package m

import (
	"GameServer/Common/utils"
	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"

	"github.com/globalsign/mgo/bson"
)

//
type AdRewards struct {
	BaseM
	Uid     string      `bson:"_id" json:"_id"`
	Rewards []*AdReward `bson:"rewards" json:"rewards"`
}

type AdReward struct {
	Typ      int64 `bson:"typ" json:"typ"`           // 类型  1 日常 广告 2 体力  3 金币 4 祭坛
	WatchNum int64 `bson:"watchNum" json:"watchNum"` // 观看次数
	Time     int64 `bson:"time" json:"time"`         //
	AltarNum int64 `bson:"altarNum" json:"altarNum"` // 祭坛领取次数
}

func NewAdRewards() cache.EntryI {
	return &AdRewards{Rewards: make([]*AdReward, 0)}
}

// 保存信息
func (ad *AdRewards) Save() (err error) {
	if ad.Rewards == nil || len(ad.Rewards) == 0 {
		return
	}
	//
	err = dbmodule.MgoDB.GameDB.Upsert("adRewards", bson.M{"_id": ad.Uid}, ad)
	if err != nil {
		return
	}
	return
}

func (ad *AdRewards) Load(key interface{}) (err error) {
	ad.Uid = key.(string)
	return ad.LoadData()
}

// 加载数据
func (ad *AdRewards) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne("adRewards", bson.M{"_id": ad.Uid}, nil, &ad)
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		return
	}
	if ad.Rewards == nil {
		ad.Rewards = make([]*AdReward, 0)
	}
	return
}

func (ad *AdRewards) GetAdReward(typ int64) (r *AdReward) {
	nowTime := utils.TNow().Unix()
	for _, item := range ad.Rewards {
		if item.Typ == typ && utils.IsSameDay(item.Time, nowTime) {
			return item
		}
	}
	return &AdReward{Typ: typ, WatchNum: 0}
}

func (ad *AdRewards) UpdateAdReward(typ int64, num int64) {
	defer ad.Update(ad)
	nowTime := utils.TNow().Unix()
	for _, item := range ad.Rewards {
		if item.Typ == typ {
			item.WatchNum = num
			item.Time = nowTime
			return
		}
	}
	ad.Rewards = append(ad.Rewards, &AdReward{Typ: typ, WatchNum: num, Time: nowTime})
}

// 更新广告 祭坛可领取信息
func (ad *AdRewards) UpdateAdRewardAltarNum(watchNum int64, altarNum int64) {
	var typ int64 = 4
	defer ad.Update(ad)
	nowTime := utils.TNow().Unix()
	for _, item := range ad.Rewards {
		if item.Typ == typ {
			item.WatchNum = watchNum
			item.Time = nowTime
			item.AltarNum = altarNum
			return
		}
	}
	ad.Rewards = append(ad.Rewards, &AdReward{Typ: typ, WatchNum: watchNum, Time: nowTime, AltarNum: altarNum})
}

// 更新数据
func (ad *AdRewards) Update(val *AdRewards) {
	Cache.Put("adRewards", ad.Uid, val)
	val.UpdateData()
}

func (u *User) GetAdRewards() (r *AdRewards) {
	v, _ := Cache.Get("adRewards", u.Uid.Hex())
	r = v.(*AdRewards)
	return
}
